package com.liuxin.mycontactdemo.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.liuxin.mycontactdemo.R;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity {
    private SharedPreferences pref;
    //private  SharedPreferences.Editor editor;
    private String pw;
    private SharedPreferences.Editor editor;
    private final String PREFS_NAME = "data";

    @InjectView(R.id.passwordET)
    EditText passwordET;
    @InjectView(R.id.loginBtn)
    Button loginBtn;
    @InjectView(R.id.resetBtn)
    Button resetBtn;
    @InjectView(R.id.remember_pass)
    CheckBox rememberPass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        //pref= PreferenceManager.getDefaultSharedPreferences(this);
        boolean isRemember=pref.getBoolean("remember_password",false);
        if(isRemember){
            //将密码设置在文本框中
            String password=pref.getString("password","");
            passwordET.setText(password);
            rememberPass.setChecked(true);
        }
    }

    @OnClick({R.id.loginBtn, R.id.resetBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.loginBtn:
                String inputPwd = passwordET.getText().toString();
                pw = pref.getString("password", "123456");
                //如果密码是123456就登陆成功
                SharedPreferences.Editor editor = pref.edit();
                //editor=pref.edit();
                if(rememberPass.isChecked()){
                    //检查复选框是否被选中
                    editor.putBoolean("remember_password",true);
                    //editor.putString("password",inputPwd);
                }else{
                    //editor.clear();
                    editor.putBoolean("remember_password", false);
                }
                editor.apply();
                if(inputPwd.equals(pw)){
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "密码输入错误，请重新输入！", Toast.LENGTH_LONG).show();
                    passwordET.setText("");
                }
                break;
            case R.id.resetBtn:
                passwordET.setText("");
                break;
        }
    }
}
